<!-- ERC-备件管理-备件出库页面 -->
<template>
  <div>
    <div class="equip-wrap-common">
      <TypeTree v-model:typeCode="typeCode" v-model:hasChildren="hasChildren" />
      <!-- 右侧整体功能 -->
      <div class="equip-table-wrap">
        <px-form class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
          <px-row :gutter="16">
            <px-col :span="10">
              <px-form-item label="保养项目名称">
                <px-input
                  v-model="queryParams.name"
                  placeholder="请输入保养项目名称"
                  autocomplete="off"
                  maxlength="50"
                  clearable
                  @blur="queryParams.name = $event.target.value.trim()"
                  @keyup.enter="queryTable"
                >
                  <template #suffix>
                    <px-icon style="cursor: pointer" @click="queryTable">
                      <search />
                    </px-icon>
                  </template>
                </px-input>
              </px-form-item>
            </px-col>
            <px-col :span="8">
              <px-button type="primary" @click="queryTable">查询</px-button>
              <px-button @click="resetTable">重置</px-button>
            </px-col>
          </px-row>
        </px-form>
        <div class="equip-table-btn">
          <px-button v-has="'ERC_EPM_ITEMS_ADD'" :disabled="hasChildren" style="margin-right: 16px" type="primary" @click="handleAdd">
            新增保养项目
          </px-button>
        </div>
        <px-table :data="tableData" class="equip-table" size="small" height="calc(100vh - 304px)" border>
          <px-table-column type="index" label="序号" min-width="60" align="center" fixed="left" />
          <px-table-column
            v-for="(item, index) in tableColumns"
            :key="index"
            :label="item.label"
            :min-width="item.minWidth"
            :align="item.align"
            :show-overflow-tooltip="item.showOverflowTooltip"
            :fixed="item.fixed"
          >
            <!-- 文档名称 -->
            <template v-if="item.type === 'file'" #default="scope">
              <div v-if="scope.row.attachmentList?.length !== 0">
                <span v-for="(item, index) in scope.row.attachmentList" :key="item.id">
                  <span v-if="isHasPermission('ERC_EPM_ITEM_PREVIEW')" style="color: #3b82f6; cursor: pointer" @click="toFilePreview(item)">
                    {{ item.originalName }}{{ scope.row.attachmentList?.length > 1 && index !== scope.row.attachmentList?.length - 1 ? "，" : "" }}
                  </span>
                  <span v-else>
                    {{ item.originalName }}
                    {{ scope.row.attachmentList?.length > 1 && index !== scope.row.attachmentList?.length - 1 ? "，" : "" }}
                  </span>
                </span>
              </div>
              <span v-else>-</span>
            </template>
            <template v-else #default="scope">
              <span>{{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}</span>
            </template>
          </px-table-column>
          <px-table-column fixed="right" label="操作" min-width="180" align="center">
            <template #default="scope">
              <px-tooltip content="编辑" placement="top">
                <px-button v-has="'ERC_EPM_ITEMS_EDIT'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
              </px-tooltip>
              <px-tooltip content="复制" placement="top">
                <px-button v-has="'ERC_EPM_ITEMS_COPY'" link type="primary" icon="DocumentCopy" @click="handleCopy(scope.row)" />
              </px-tooltip>
              <px-tooltip content="删除" placement="top">
                <px-button v-has="'ERC_EPM_ITEMS_DELETE'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>
        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          class="equip-table-pagination"
          :total="total"
          @pagination="queryTable"
        />
      </div>
    </div>
    <!-- 新增弹窗 -->
    <px-dialog v-model="isShow" :title="formValue.id ? '修改保养项目' : '新增保养项目'" width="900px" destroy-on-close append-to-body @close="cancel">
      <px-form ref="formRef" :model="formValue" :rules="rules" label-width="120px">
        <px-form-item label="保养项目名称" prop="name">
          <px-input v-model="formValue.name" maxlength="50" clearable placeholder="请输入保养项目名称" />
        </px-form-item>
        <px-form-item label="备注" prop="standard">
          <px-input
            v-model="formValue.standard"
            type="textarea"
            placeholder="请输入备注"
            :autosize="{ minRows: 2, maxRows: 4 }"
            maxlength="1000"
            clearable
          />
        </px-form-item>
        <px-form-item label="保养标准" prop="attachmentList">
          <FileUpload
            :countLimit="10"
            fileType="add"
            :fileData="{ moduleName: moduleName }"
            fileTitle="保养标准"
            fileTypeValue="word pdf excel"
            :fileLists="fileList"
            :fileSize="100"
            fileAccept=".doc,.docx,.pdf,.xlsx,.xls"
            @changeFileList="changeFileList"
          />
        </px-form-item>
        <px-form-item label="确认方式" prop="confirmWay">
          <px-select v-model="formValue.confirmWay" disabled placeholder="请选择确认方式" style="width: 100%">
            <px-option v-for="item in wayList" :key="item.id" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item>
      </px-form>
      <template #footer>
        <div class="dialog-footer">
          <px-button @click="cancel">取 消</px-button>
          <px-button type="primary" @click="submitForm(formRef)">保 存</px-button>
        </div>
      </template>
    </px-dialog>
    <px-dialog
      v-model="previewDialogVisible"
      title="预览"
      width="1200px"
      @close="
        previewDialogVisible = false;
        previewFile = null;
      "
    >
      <iframe :src="previewFile" width="100%" height="600px" frameborder="0" />
      <div style="width: 100%; margin-top: 24px; text-align: right">
        <px-button
          @click="
            previewDialogVisible = false;
            previewFile = null;
          "
          >关闭</px-button
        >
      </div>
    </px-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ERC_EPM_ITEMS"
});
import { queryDictData } from "@/api/common";
import { addItems, delItems, getModuleName, queryItemsList, updateItems } from "@/api/erc/epm";
import { getToken, isHasPermission } from "@/utils/auth";
import axios from "axios";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, onMounted, reactive, ref, toRefs, watch } from "vue";
import FileUpload from "./components/FileUpload.vue";
import TypeTree from "./components/TypeTree.vue";

const formRef = ref();
const { proxy }: any = getCurrentInstance();

const validateAttach = (rule, value, callback) => {
  if (fileList.value.length <= 0) {
    callback(new Error("附件不能为空"));
  }
  callback();
};

const state = reactive<any>({
  formValue: {
    confirmWay: "1"
  },
  queryParams: {
    pageNum: 1,
    pageSize: 20
  },
  tableColumns: [
    { prop: "name", label: "保养项目名称", minWidth: "220", showOverflowTooltip: true, fixed: "left" },
    { prop: "standard", label: "保养标准", minWidth: "350", type: "file", showOverflowTooltip: true },
    { prop: "confirmWayName", label: "确认方式", minWidth: "150", showOverflowTooltip: true },
    { prop: "createByName", label: "创建人", minWidth: "130", showOverflowTooltip: true },
    { prop: "createTime", label: "创建时间", minWidth: "200", showOverflowTooltip: true }
  ],
  rules: {
    name: [{ required: true, message: "保养项目名称不能为空", trigger: "blur" }],
    attachmentList: [{ required: true, validator: validateAttach, trigger: "blur" }]
  },
  tableData: [],
  total: 0,
  isShow: false,
  wayList: [], // 确认方式列表
  typeCode: "",
  hasChildren: true,
  moduleName: "",
  fileList: [],
  previewDialogVisible: false,
  previewFile: null
});
const {
  formValue,
  rules,
  queryParams,
  tableColumns,
  tableData,
  total,
  isShow,
  wayList,
  typeCode,
  hasChildren,
  moduleName,
  fileList,
  previewDialogVisible,
  previewFile
} = toRefs(state);

// 获取getModuleName
const getModuleNameValue = async () => {
  moduleName.value = await getModuleName();
};

// 进入页面时触发
onMounted(async () => {
  getModuleNameValue();
  wayList.value = await queryDictData({ typeCode: "ERC_MAINTAIN_PROJECT_CONFIRM_WAY" });
  queryTable();
});

watch(
  () => typeCode.value,
  (newVal, oldVal) => {
    if (newVal) {
      queryTable();
    }
  }
);

// 预览文件
const toFilePreview = (item: any) => {
  if (!["pdf", "doc", "docx", "xls", "xlsx"].includes(item.fileType)) {
    PxMessage.error("暂不支持该格式文件的预览");
    return;
  }
  if (item.fileType === "pdf") {
    const params = {
      id: item.id
    };
    axios({
      method: "post",
      url: "/ifp/sharing/api/v1/file/download",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + getToken().accessToken || "",
        facCode: localStorage.getItem("facCode") || ""
      },
      data: params,
      responseType: "arraybuffer"
    }).then(res => {
      previewFile.value = URL.createObjectURL(new Blob([res.data], { type: "application/pdf;chartset=utf-8" }));
      previewDialogVisible.value = true;
    });
  } else {
    const params = {
      id: item.id,
      fileName: item.fileName
    };
    proxy.download("post", "/sharing/api/v1/file/download", params, item.originalName);
  }
};

const changeFileList = val => {
  fileList.value = val;
  formRef?.value?.clearValidate("attachmentList");
};

// 查询
const queryTable = async () => {
  const params = JSON.parse(JSON.stringify(queryParams.value));
  const data = await queryItemsList({ ...params, typeCode: typeCode.value });
  tableData.value = data?.data || [];
  total.value = data?.total;
};
// 重置筛选条件
const resetTable = async () => {
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  queryTable();
};
// 添加
const handleAdd = () => {
  formValue.value.confirmWay = "1";
  isShow.value = true;
};
// 编辑
const handleEdit = (row: any) => {
  isShow.value = true;
  const temp = JSON.parse(JSON.stringify(row));
  formValue.value = { ...formValue.value, ...temp };
  fileList.value = formValue.value.attachmentList || [];
};
// 复制
const handleCopy = (row: any) => {
  isShow.value = true;
  const temp = JSON.parse(JSON.stringify(row));
  formValue.value = { ...formValue.value, ...temp };
  fileList.value = formValue.value.attachmentList || [];
  delete formValue.value.id;
};
// 删除
const handleDelete = async (row: any) => {
  PxMessageBox.confirm(`要删除当前保养项目吗？`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const params = {
        idList: [row.id]
      };
      await delItems(params);
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
/** 取消按钮 */
const cancel = () => {
  fileList.value = [];
  formRef.value.resetFields();
  formValue.value = {};
  isShow.value = false;
};
/** 提交按钮 */
const submitForm = async (formEl: any, type?: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const attachmentList = [];
      if (fileList.value && fileList.value.length > 0) {
        fileList.value.forEach(item => {
          if (item?.id) {
            attachmentList.push(item.id);
          } else if (item?.response.data.id) {
            attachmentList.push(item.response.data.id);
          }
        });
      }
      if (formValue.value.id) {
        updateItems({ ...formValue.value, attachmentList }).then(() => {
          PxMessage.success("修改成功");
          cancel();
          queryTable();
        });
      } else {
        addItems({ typeCode: typeCode.value, ...formValue.value, attachmentList }).then(() => {
          PxMessage.success("新增成功");
          cancel();
          queryTable();
        });
      }
    }
  });
};
</script>

<style lang="scss" scoped>
@import url("@/views/erc/scss/table-flex-list.scss");
</style>
